package br.com.basili.dao;

import java.util.List;

import org.hibernate.Query;

import br.com.basili.entity.Protocol;
import br.com.basili.hibernateUtil.ConexaoHibernate;

public class ProtocoloDAO extends GenericDAO<Protocol>{
	
	public List<Protocol> getListProtocol() throws Exception{
		return super.getListaModel("from Protocol");
	}
	
	public Protocol getProtocolPorCodigo( int codigo ) throws Exception{
		
		StringBuilder sql = new StringBuilder();
		sql.append( "Select p from Protocol p " );
		sql.append( "where p.codigo = :codigo"  );

		s = ConexaoHibernate.sessionFactory.openSession();
		tr = s.beginTransaction();
		
		return (Protocol) s.load(Protocol.class, codigo);
		
		
//		Query query = s.createQuery(sql.toString());
//					
//		query.setParameter("codigo", codigo );
//		
//		return (Protocol)query.uniqueResult();
	}
	
	public  List<Protocol> getListProtocolPorParam(String titutlo, String tema, String nome) throws Exception{
		
		StringBuilder sql = new StringBuilder();
		sql.append("Select protocol from Protocol protocol ");
		sql.append(" where 1=1 ");		
		sql.append(titutlo.length() < 3 ? "" : " and protocol.identification.title like :titulo ");		
		sql.append(tema.length()    < 3 ? "" : " and protocol.identification.theme like :tema ");		
//		sql.append(nome         == null ? "" : " and protocol.identification.researchers in ( :nome ) ");	
		
		s = ConexaoHibernate.sessionFactory.openSession();
		tr = s.beginTransaction();
		
		Query query = s.createQuery(sql.toString());
					
		if (titutlo.length() > 2) 
			query.setParameter("titulo", "%" + titutlo + "%" );
		if (tema.length() > 2) 
			query.setParameter("tema", "%" + tema + "%" );
//		if (nome != null ) 
//			query.setParameter("nome", nome );
			
		List<Protocol> lista = (List<Protocol>)query.list();
		
		s.close();
		
		return lista;	
		}
	
	public void salvar( Protocol p ){
		try {
			super.salvar(p);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
